<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="650" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" >
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="UserForm">
  import {ref, computed, unref,useAttrs} from 'vue';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import {formSchema} from './user.data';
  import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import {saveOrUpdateUser, getUserDetails} from '/@/api/member/user.api';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const rowId = ref('');
  const [registerForm, {setProps,resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol: {lg: 24, sm: 24} 
  });
  
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    console.timeEnd('user-drawer')
    
    await resetFields();
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter })
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setDrawerProps({ loading: true })
      try {
        rowId.value = data.record.id;
        try {
          data.record = await getUserDetails({id: data.record.id});
        } catch (error) {
        }
        if (typeof data.record === 'object') {
          setFieldsValue({
            ...data.record,
          })
        }
      } finally {
        setDrawerProps({ loading: false })
      }
    }

    updateSchema([
      {
        field: 'password',
        show: !unref(isUpdate),
      },
      {
        field: 'confirmPassword',
        ifShow: !unref(isUpdate),
      }
    ]);
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter })
  });
  //获取标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增会员' : '编辑会员'));

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});
      values.userIdentity === 1 && (values.deptIds='');
      await saveOrUpdateUser(values, unref(isUpdate));
      closeDrawer();
      emit('success', {isUpdate: unref(isUpdate), values: {...values, id: rowId.value}});
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
